package com.china.produce.message;

import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2025/6/24
 */
public class SseEmitterMessageSender {

    private static final Map<Object, SseEmitter> SESSION_CACHE = new ConcurrentHashMap<>();

    public static void send(Object sessionKey, String message) {
        SseEmitter emitter = SESSION_CACHE.get(sessionKey);
        if (emitter != null) {
            try {
                emitter.send(message);
            } catch (IOException e) {
                SESSION_CACHE.remove(sessionKey);
            }
        }
    }

    public static void broadcast(String message) {
        SESSION_CACHE.values().forEach(emitter -> {
            try {
                emitter.send(message);
            } catch (IOException e) {
                emitter.completeWithError(e);
            }
        });
    }

    public static void addSession(Object key, SseEmitter emitter) {
        SESSION_CACHE.put(key, emitter);
    }

    public static void removeSession(Object key) {
        SESSION_CACHE.remove(key);
    }
}
